﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using VodafoneLiveTile;


namespace H3GLiveTile.Connections
{
    public class BasicConnection
    {

        protected CookieContainer cookieJar;
        protected ConnectionQueue connections;
        protected Action<HttpWebResponse> BasicConnectionCallBack;
        protected Action onConnectionError;
        protected Action onCompletion;
        protected VodafoneResult result;

        
        public BasicConnection()
        {
            connections = new ConnectionQueue();
            cookieJar = new CookieContainer();
            result = new VodafoneResult();
        }

        public BasicConnection(VodafoneResult result, string username, string password, string number, bool isFirstNumber, Action<HttpWebResponse> basicConnectionCallBack, Action onConnectionError, Action<HttpWebResponse> onCompletion)
        {
            this.result = result;
            connections = new ConnectionQueue();
            cookieJar = new CookieContainer();
            this.onConnectionError = onConnectionError;
            this.BasicConnectionCallBack = basicConnectionCallBack;


            var login_url = "http://fboscari.altervista.org/H3G/H3GCheckUsernamePassword.php?username=" + HttpUtility.UrlEncode(username) + "&password=" + HttpUtility.UrlEncode(password);
            connections.AddConnection(new ConnectionGET()
            {
                url = login_url,
                CookieContainer = cookieJar,
                prevProcessor = (_) => { },
                currProcessor = (response)=>{
                    basicConnectionCallBack(response);
                    if (onCompletion != null)
                        onCompletion(response);
                },
                onError = OnConnectionError
            });
        }

        public void OnConnectionError()
        {
            Stop();
            result.failed = true;
            if (onConnectionError != null)
                onConnectionError();
        }
        public void Start()
        {
            connections.Run();
        }
        public void Stop()
        {
            connections.Stop();
            result.failed = true;
        }
        public int GetConnectionsCount()
        {
            return connections.connections.Count;
        }

        public CookieContainer GetCookieContainer()
        {
            return cookieJar;
        }
        public void SetCookieContainer(CookieContainer cookieJar)
        {
            this.cookieJar = cookieJar;
        }
    }
}
